<template>
  <div class="container">
    <div class="top">
      <el-row :gutter="20" class="top-search">
        <el-col :span="7">
          <el-input
            placeholder="请输入文章名字..."
            v-model="queryForm.query"
            clearable
          ></el-input>
        </el-col>
        <el-button type="primary" :icon="Search" @click="initArticleList">
          搜索
        </el-button>
      </el-row>
    </div>
    <div class="bottom">
      <el-table :data="tableData" style="width: 100%;">
        <el-table-column prop="id" label="id" width="180" />
        <el-table-column prop="title" label="文章标题" width="180" />
        <el-table-column prop="cover" label="文章封面" align="center">
          <template #default="scope">
            <img :src="scope.row.cover" width="80" />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="150"/>
        <el-table-column
          label="文章操作"
          align="center"
          fixed="right"
        >
          <template #default="scope">
              <el-button
                type="success"
                @click="handleArticleEditor(scope.row.id)"
              >
                编辑
              </el-button>
              <el-button 
                type="danger"
                @click="handleArticleRemoval(scope.row.id)"
              >
                下架
              </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页栏 -->
      <el-pagination
        v-model:current-page="queryForm.pageCurrent"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[5, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive} from 'vue'
import { Search } from "@element-plus/icons-vue";
import {articleApi} from '@/api/article.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import {useRouter} from 'vue-router'

//### 变量定义 ###
const router = useRouter(); //路由参数
const emit = defineEmits(['update-article']);  //获取父组件提供的操作菜单的方法
const total = ref(0); //分页总条目数
const queryForm = reactive({ //分页查询参数
  query: "",
  pageCurrent: 1,
  pageSize: 5,
});

const tableData = ref()

//### 方法定义 ###
//页面初始化数据方法
const initArticleList = async () => {
  try {
    const result = await articleApi.articlePagingConditionQuery(queryForm);
    if(result.code === 200) {
      tableData.value = result.data.articleManageVOList;
      total.value = parseInt(result.data.total, 10);  //注意这里获取的是字符串不是数字
    }else {
      ElMessage({
        message: '初始化数据失败，检查网络或后端服务未启动',
        type: 'error',
        plain: true,
      })
    }
  }catch(e) {
    tableData.value = [  //表单数据
        {
          id: '1111111111111111111',
          title: 'Java攻城狮修炼手册',
          cover: 'http://minio-server:9000/images/cover/cover.jpg',
          createTime: '2016-05-02',
        },
                {
          id: '1111111111111111111',
          title: 'Java攻城狮修炼手册',
          cover: 'http://minio-server:9000/images/cover/cover.jpg',
          createTime: '2016-05-02',
        },
                {
          id: '1111111111111111111',
          title: 'Java攻城狮修炼手册',
          cover: 'http://minio-server:9000/images/cover/cover.jpg',
          createTime: '2016-05-02',
        },
                {
          id: '1111111111111111111',
          title: 'Java攻城狮修炼手册',
          cover: 'http://minio-server:9000/images/cover/cover.jpg',
          createTime: '2016-05-02',
        },
        {
          id: '2',
          title: 'Java攻城狮修炼手册',
          cover: 'http://minio-server:9000/images/cover/cover.jpg',
          createTime: '2016-05-02',
        },
        // {
        //   id: '3',
        //   title: 'Java攻城狮修炼手册',
        //   cover: 'http://minio-server:9000/images/cover/cover.jpg',
        //   createTime: '2016-05-02',
        // },
        // {
        //   id: '4',
        //   title: 'Java攻城狮修炼手册',
        //   cover: 'http://minio-server:9000/images/cover/cover.jpg',
        //   createTime: '2016-05-02',
        // },
        // {
        //   id: '5',
        //   title: 'Java攻城狮修炼手册',
        //   cover: 'http://minio-server:9000/images/cover/cover.jpg',
        //   createTime: '2016-05-02',
        // },
    ]
    total.value = tableData.value.length;
    ElMessage({
      message: '请求方式初始化失败，显示默认数据',
      type: 'error',
      plain: true,
    })
  }
}

//### 初始化调用
initArticleList();

//文章编辑
const handleArticleEditor = (id:any) => {
  console.log('获取的id是', id);
  emit('update-article', id); //点击修改后通知父组件，并将选择的文章id传递过去
}

//文章修改
const handleArticleRemoval = (id:any) => {
  // console.log('获取的id是', id);
  ElMessageBox.confirm(
    '删除数据后无法恢复，你确定要删除?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      console.log("我运行了")
      const result = await articleApi.deleteArticle({"id":id});
      console.log("看看删除返回结果", result)
      if(result.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        initArticleList();
      }else {
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

// 监听当前页，和每页条数变化
const handleSizeChange = (pageSize:any) => {
  queryForm.pageCurrent = 1;
  queryForm.pageSize = pageSize;
  initArticleList(); //重新初始化一下
};

const handleCurrentChange = (pageCurrent:any) => {
  queryForm.pageCurrent = pageCurrent;
  initArticleList(); //重新初始化一下
};

</script>

<style scoped lang="scss">
.container {
  height: 85vh;
  display: flex;
  flex-direction: column;
  overflow-y: auto;      /* 整体滚动 */
  // background: green;

  /* 关键：允许子项收缩 */
  > * {
    min-height: 0;     /* 覆盖 Flex 默认的 min-height: auto */
  }

  .top {
    flex-shrink: 0;    /* 固定高度（不拉伸） */
    // background: indianred;
    
    .top-search {
      padding: 16px;
      box-sizing: border-box;
    }
  }

  .bottom {
    flex: 1;           /* 占满剩余空间，这里也不要设置高度，里面的内容如果多了自然可以滑动 */
    // background: indigo;

    .el-pagination {
      margin-top: 20px;
    }
  }
}
</style>